package src.login.dao;

import cn.hutool.crypto.SecureUtil;
import src.util.Dbutil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    /**
     * 用户登录
     * @param username 账号
     * @param pass 密码
     * @return 成功返回 true，失败返回 false
     */
    public boolean login(String username,String pass){
        boolean flag;
        Connection conn;
        conn = Dbutil.getConnection();
        String sql = "SELECT * FROM user WHERE username=? AND userpass=?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,SecureUtil.md5(pass));
            ResultSet rs = pstmt.executeQuery();
            flag =rs.next();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            Dbutil.clossConn(conn);
        }
        return flag;
    }

    /** 用户注册
    * @param username 用户名
    * @param userpass 密码
    * @return 成功返回1 否则返回0
    * */
    public int addUser(String username,String userpass){
        int flag;
        Connection conn;
        conn= Dbutil.getConnection();
        //定义sql语句
        String sql="insert into user (username,userpass) values(?,?)";
        //准备sql语句
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);

            pstmt.setString(1,username);
            pstmt.setString(2, SecureUtil.md5(userpass));
            //执行sql语句
            flag = pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            Dbutil.clossConn(conn);
        }
        return flag;
    }
}
